package com.cm.sys.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cm.sys.system.entity.Menu;
import com.cm.sys.system.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cm.sys.framework.application.ApiResponseCode;
import com.cm.sys.framework.application.RequestParameter;
import com.cm.sys.framework.application.ResponseResult;
import com.cm.sys.framework.execption.BusinessException;
import com.cm.sys.framework.utils.DateUtil;
import com.cm.sys.framework.utils.JsonUtil;
import com.cm.sys.system.entity.RoleAuth;
import com.cm.sys.system.service.RoleAuthService;

/***
 * 权限管理
 * 
 * @author yxq18
 *
 */
@Controller
@RequestMapping(value = "/user")
public class RoleAuthController {

    private static final Logger logger = LoggerFactory.getLogger(RoleAuthController.class);

    @Autowired
    private RoleAuthService roleAuthService;

    @Autowired
    private MenuService menuService;

    /***
     * 查询权限
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public ResponseResult getUser(RequestParameter rp) {

        JSONObject args = rp.getparameters();

        ResponseResult rr = new ResponseResult();
        List<RoleAuth> list = roleAuthService.selectAuths(args);

        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("lists", list);
        rr.setMap(map);
        return rr;

    }

    /***
     * 查询权限
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/auth/{id}", method = RequestMethod.GET)
    public ResponseResult getUser(RequestParameter rp, @PathVariable("id") String id) {

        ResponseResult rr = new ResponseResult();

        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(), "路由错误缺少id");
        }
        List<Integer> list = roleAuthService.getAuths(Integer.parseInt(id));

        Map map = new HashMap<String, Object>(16);
        map.put("lists", list);
        rr.setMap(map);
        return rr;

    }

    /***
     * 删除权限
     * 
     * @return
     */
    @RequestMapping(value = "/auth/{id}", method = RequestMethod.DELETE)
    public ResponseResult deleteUser(RequestParameter rp, @PathVariable("id") String id) {
        ResponseResult rr = new ResponseResult();
        System.out.println("***************入参*********"+rp);
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(), "路由错误缺少id");
        }
        int count = roleAuthService.delAuth(rp.getparameters(), Integer.parseInt(id));
        if (count != 1) {
            rr.setCode(ApiResponseCode.NO_DEL_DATA.getCode());
        }

        return rr;

    }

    /***
     * 更新权限
     * 
     * @param rp
     * @return
     */
    @RequestMapping(value = "/auth/{id}", method = RequestMethod.PUT)
    public ResponseResult putUser(RequestParameter rp, @PathVariable("id") String id) {
        ResponseResult rr = new ResponseResult();
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(), "路由错误缺少id");
        }
        RoleAuth roleAuth = roleAuthService.updateAuth(rp.getparameters(), Integer.parseInt(id));
        rr.setObject(roleAuth);
        return rr;
    }

    /***
     * 编辑用户权限
     *  修改：避免删除根目录，所以在编辑时要检测，新保存的权限列表中都有所有的根目录，否则不允许修改
     * @param rp
     * @return
     */

    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public ResponseResult postAuth(RequestParameter rp) {
        ResponseResult rr = new ResponseResult();

        JSONArray args = JsonUtil.getJSONArray(rp.getparameters(), "lists");



        logger.info("=======新增权限====={}=============", args);
        List<Map> list = JSON.parseArray(args.toJSONString(), Map.class);
        List<RoleAuth> listRa = new ArrayList<RoleAuth>();
        int roleId = 0;
        for (Map map : list) {
            RoleAuth ra = new RoleAuth();
            ra.setMenuId((Integer)map.get("menuId"));
            ra.setRoleId((Integer)map.get("roleId"));
            ra.setCreateTime(DateUtil.getTimestamp());
            ra.setUpdateTime(DateUtil.getTimestamp());
            listRa.add(ra);
            roleId = (Integer)map.get("roleId");
        }
        //查询出所有的根目录
        List<Menu> rootMenus= menuService.selectRootMenus();
        //判断新保存的权限列表中是否都有这些目录
        boolean hasRootMenu=CheckRootMenus(rootMenus,listRa);
        if(hasRootMenu){
            logger.info("=======新增权限的权限id====={}=============", roleId);
            roleAuthService.delAuth(rp.getparameters(),roleId);
            roleAuthService.saveAuth(listRa);
            return rr;
        }else{
            throw new BusinessException(ApiResponseCode.DEL_FAIL.getCode(),"不允许删除根目录");
        }


    }
    //检查修改后的权限列表中，是否有根目录
    private boolean CheckRootMenus(List<Menu> rootMenus, List<RoleAuth> listRa) {
        int cnt = 0;
        for (RoleAuth roleAuth : listRa) {
            for (Menu rootMenu : rootMenus) {
                if(rootMenu.getId().equals(roleAuth.getMenuId()) ){
                    cnt++;
                }
            }
        }
        if(cnt == rootMenus.size()){
            return true;
        }
        return false;
    }

}
